const app = getApp()
// const apiHttp = "http://129.211.29.77:32774";
const apiHttp = "https://www.brace.vin";
// const apiHttp = "http://localhost:3000";
const socketHttp = "wss://*****.com/wss";
function fun(url, method, data, header) {
    data = data || {};
    header = header || {};
    let session_id = wx.getStorageSync("session_id");
    if (session_id) {
        if (!header["session_id"]) {
            header["session_id"] = session_id;
        }
    }
    wx.showNavigationBarLoading();
    let promise = new Promise(function (resolve, reject) {
        wx.request({
            url: apiHttp + url,
            header: header,
            data: data,
            method: method,
            success: function (res) {
                if (typeof res.data === 'object') {
                    if (res.data.code) {
                        if (res.data.code === '401') {
                            wx.showToast({
                                title: res.data.msg,
                                icon: "none"
                            });
                            wx.navigateTo({
                                url: '/pages/login'
                            })
                            reject("请求失败");
                        }
                        if (res.data.code !== '0') {
                            wx.showToast({
                                title: res.data.msg,
                                icon: "none"
                            });
                            reject("请求失败");
                        }
                    }
                }
                resolve(res.data);
            },
            fail: reject,
            complete: function () {
                wx.hideNavigationBarLoading();
            }
        });

    });
    return promise;
}
function upload(url, name, filePath) {
    let header = {};
    let session_id = wx.getStorageSync("session_id"); //从缓存中拿该信息
    if (session_id) {
        if (!header || !header["session_id"]) {
            header["session_id"] = session_id; //添加到请求头中
        }
    }
    wx.showNavigationBarLoading();
    let promise = new Promise(function (resolve, reject) {
        wx.uploadFile({
            url: apiHttp + url,
            filePath: filePath,
            name: name,
            header: header,
            success: function (res) {
                resolve(res.data);
            },
            fail: reject,
            complete: function () {
                wx.hideNavigationBarLoading();
            }
        });
    });
    return promise;
}
module.exports = {
    apiHttp: apiHttp,
    socketHttp: socketHttp,
    get: function (url, data, header) {
        return fun(url, "GET", data, header);
    },
    post: function (url, data, header) {
        return fun(url, "POST", data, header);
    },
    upload: function (url, name, filePath) {
        return upload(url, name, filePath);
    }
};